package com.yxq.mdt.app.modules.socialcontact.ui.activity;

import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.hyphenate.chat.EMCallStateChangeListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.EMNoActiveCallException;
import com.hyphenate.exceptions.EMServiceNotReadyException;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.media.EMCallSurfaceView;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.constant.Constant;
import com.yxq.mdt.app.dialog.CostumerDialog;
import com.yxq.mdt.app.glide.GlideHelper;
import com.yxq.mdt.app.modules.bottomsheet.GiveListBottomSheetDialogFragment;
import com.yxq.mdt.app.modules.bottomsheet.LiveEndCallSheetDialogFragment;
import com.yxq.mdt.app.modules.personal.bean.MyPersonalBean;
import com.yxq.mdt.app.modules.personal.model.MainPersonalModel;
import com.yxq.mdt.app.modules.personal.model.UserModel;
import com.yxq.mdt.app.modules.personal.ui.activity.RechargeActivity;
import com.yxq.mdt.app.modules.socialcontact.bean.GivePresentBean;
import com.yxq.mdt.app.modules.socialcontact.bean.LiveResultBean;
import com.yxq.mdt.app.modules.socialcontact.bean.SocialPersonalHomepageBean;
import com.yxq.mdt.app.modules.socialcontact.model.LiveModel;
import com.yxq.mdt.app.modules.socialcontact.model.MainSocialContactModel;
import com.yxq.mdt.app.modules.socialcontact.presenter.ILiveContract;
import com.yxq.mdt.app.modules.socialcontact.presenter.LivePresenter;
import com.yxq.mdt.app.modules.withdraw.bean.WithDrawResultBean;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.PhoneStateManager;
import com.yxq.mdt.app.utils.StringUtils;
import com.yxq.mdt.app.widgets.CircleImageView;

import java.util.Collection;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 视频邀请方
 */
public class VideoInviteChatActivity extends CallActivity<LivePresenter> implements ILiveContract.View {

    @BindView(R.id.local_surface_image)
    CircleImageView localSurfaceImage;
    @BindView(R.id.video_tv_nick_name)
    TextView videoTvNickName;
    @BindView(R.id.video_tv_hint)
    TextView videoTvHint;
    @BindView(R.id.btn_answer)
    ImageView btnAnswer;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.open_chat_lint_in_one)
    RelativeLayout openChatLintInOne;
    @BindView(R.id.opposite_surface_two)
    EMCallSurfaceView oppositeSurfaceTwo;
    @BindView(R.id.local_surface_two)
    EMCallSurfaceView localSurfaceTwo;
    @BindView(R.id.layout_alert_layout)
    LinearLayout layoutAlertLayout;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.btn_present_two)
    ImageView btnPresentTwo;
    @BindView(R.id.video_layout_gift)
    LinearLayout videoLayoutGift;
    @BindView(R.id.btn_switch_two)
    ImageView btnSwitchTwo;
    @BindView(R.id.btn_transition_two)
    ImageView btnTransitionTwo;
    @BindView(R.id.tv_status_two)
    TextView tvStatusTwo;
    @BindView(R.id.open_chat_lint_in_two)
    RelativeLayout openChatLintInTwo;
    EMCallStateChangeListener callStateListener; //通话状态监听器
    CountDownTimer countDownTimer;
    String userId;
    String liveId;
    MyPersonalBean mMyPersonalBean;
    double giftPrice = 0d;
    LiveEndCallSheetDialogFragment liveEndCallSheetDialogFragment;
    private boolean isMuteState;
    private boolean isHandsfreeState;

    @Override
    public int getLayoutId() {
        setStatusBarDarkFont(false);
        setEnableImmersion(true);
        setStatusBarColor(R.color.black);
        return R.layout.activity_inviter_await_video_chat;
    }

    @Override
    public void onBackPressed() {

    }

    @Override
    public void initView() {
        super.initView();
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

        localSurfaceTwo.setZOrderMediaOverlay(true);
        localSurfaceTwo.setZOrderOnTop(true);
        //设置Surface
        EMClient.getInstance().callManager().setSurfaceView(localSurfaceTwo, oppositeSurfaceTwo);
        addCallStateListener();
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        mPresenter = new LivePresenter(this, new LiveModel());
        if (getIntent().getStringExtra("userId") != null) {
            userId = getIntent().getStringExtra("userId").replaceAll("yxq", "");
        }
        //查询其他人用户信息
        UserModel.getGaUserExtVoById(userId, new ApiModel.CommonCallback<MyPersonalBean>() {
            @Override
            public void onSuccess(MyPersonalBean socialPersonalHomepageBean) {
                mMyPersonalBean = socialPersonalHomepageBean;
                if (socialPersonalHomepageBean.getGsName() != null) {
                    TextView tvName = findViewById(R.id.video_tv_nick_name);
                    tvName.setText(socialPersonalHomepageBean.getGsName());
                }
                CircleImageView avatar = findViewById(R.id.local_surface_image);
                GlideHelper.load(VideoInviteChatActivity.this, socialPersonalHomepageBean.getHeadimg(), avatar);

                //查询自己
                MainPersonalModel.getPersonalDate(Constant.getLbsUserToken(), new ApiModel.CommonCallback<MyPersonalBean>() {
                    @Override
                    public void onSuccess(MyPersonalBean myPersonalBean) {
                        if (myPersonalBean != null) {

                            if (myPersonalBean.getMoney() > mMyPersonalBean.getVideoPrice()) {
                                try {
                                    EMClient.getInstance().callManager().makeVideoCall(getIntent().getStringExtra("userId"));
                                } catch (EMServiceNotReadyException e) {
                                    e.printStackTrace();
                                }
//                        soundPool = new SoundPool(1, AudioManager.STREAM_RING, 0);
//                        outgoing = soundPool.load(mActivity, R.raw.em_outgoing, 1);
                            } else {
                                //余额不足
                                CostumerDialog dialog = new CostumerDialog.Builder(mActivity, R.style.custom_dialog_no_match)
                                        .setContentView(R.layout.dialog_clear_cache_layout)
                                        .setCancelable(true)
                                        .create();

                                TextView title = dialog.findViewById(R.id.tv_title);

                                title.setText("余额不足");

                                TextView content = dialog.findViewById(R.id.tv_content);
                                content.setText("当前余额不足，充值后可继续送礼，是否去充值？");

                                //充值
                                TextView sure = dialog.findViewById(R.id.tv_sure);
                                sure.setText("充值");
                                sure.setOnClickListener(v -> {
                                    Intent it = new Intent(mActivity, RechargeActivity.class);
                                    startActivity(it);
                                    dialog.dismiss();
                                    finishChat();
                                });

                                //取消
                                TextView cancel = dialog.findViewById(R.id.tv_cancel);
                                cancel.setText("取消");
                                cancel.setOnClickListener(v -> {
                                    dialog.dismiss();
                                    finishChat();
                                });
                                dialog.show();
                            }
                        }
                    }

                    @Override
                    public void onError(String errMsg) {

                    }
                });
            }

            @Override
            public void onError(String errMsg) {

            }
        });

    }
    PhoneStateManager.PhoneStateCallback phoneStateCallback = new PhoneStateManager.PhoneStateCallback() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:   // 电话响铃
                    break;
                case TelephonyManager.CALL_STATE_IDLE:      // 电话挂断
                    // resume current voice conference.
                    if (isMuteState) {
                        try {
                            EMClient.getInstance().callManager().resumeVoiceTransfer();
                        } catch (HyphenateException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:   // 来电接通 或者 去电，去电接通  但是没法区分
                    // pause current voice conference.
                    if (!isMuteState) {
                        try {
                            EMClient.getInstance().callManager().pauseVoiceTransfer();
                        } catch (HyphenateException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
            }
        }
    };
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    break;
                case 2:
                    TextView textView = findViewById(R.id.video_tv_hint);
                    textView.setText("");
                    findViewById(R.id.open_chat_lint_in_one).setVisibility(View.GONE);
                    findViewById(R.id.open_chat_lint_in_two).setVisibility(View.VISIBLE);
                    startTimer();
                    // Start to watch the phone call state.
                    PhoneStateManager.get(VideoInviteChatActivity.this).addStateCallback(phoneStateCallback);
                    break;
                case 3:
                    PhoneStateManager.get(VideoInviteChatActivity.this).removeStateCallback(phoneStateCallback);
                    finishChat();
                    if (countDownTimer != null) {
                        countDownTimer.cancel();
                    }
                    removeCallStateListener();
                    break;
                case 4:
                    //拒接
                    ToastUtils.showShort("对方拒接了您的邀请");
                    break;
                case 5:
                    //对方忙
                    ToastUtils.showShort("对方正在通话中");
                    break;
                case 6:
                    //超时
                    ToastUtils.showShort("对方手机可能不在身边，请稍后再试");
                    break;
                case 7:
                    //环信账号不存在
                    ToastUtils.showShort("对方环信账号不存在");
                    break;
                case 8:
                    //对方目前不可用
                    ToastUtils.showShort("对方不在线，请稍后再试");
                    break;
            }
        }
    };

    void removeCallStateListener() {
        EMClient.getInstance().callManager().removeCallStateChangeListener(callStateListener);
    }

    /**
     * 拒绝接听
     */
    public void refuseCall() {
        try {
            EMClient.getInstance().callManager().rejectCall();
            finish();
        } catch (EMNoActiveCallException e) {
            e.printStackTrace();
            finish();
        }
    }

//    boolean isEndCall;//是否主动挂断

    /**
     * 挂断
     */
    public void newEndCall() {
        try {
            EMClient.getInstance().callManager().endCall();
        } catch (EMNoActiveCallException e) {
            e.printStackTrace();
        }
    }

    /**
     * 挂断
     */
    public void newEndCallFinish() {
        try {
            EMClient.getInstance().callManager().endCall();
        } catch (EMNoActiveCallException e) {
            e.printStackTrace();
        } finally {
            finish();
        }
    }

    /**
     * 转换摄像头
     */
    public void switchCamera() {
        EMClient.getInstance().callManager().switchCamera();
    }

    int time = 0;

    private void startTimer() {
        mPresenter.addOrUpdateVideo(userId, 1, null);
        countDownTimer = new CountDownTimer(Long.MAX_VALUE, 1000) {
            @Override
            public void onTick(long l) {
                time++;
                if ((time % 65) == 0) {
                    timerDeduction();
                }
                View view = findViewById(R.id.layout_alert_layout);
                if (time >= 5 && view.getVisibility() == View.VISIBLE) {
                    view.setVisibility(View.GONE);
                }
                TextView tvTime = findViewById(R.id.tv_time);
                tvTime.setText(StringUtils.formatTime(time));

            }

            @Override
            public void onFinish() {

            }
        };
        countDownTimer.start();
    }

    @OnClick({R.id.btn_answer, R.id.btn_transition_two, R.id.btn_present_two, R.id.btn_switch_two})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_answer:
                refuseCall();
                break;
            case R.id.btn_switch_two:
                //挂断
                newEndCall();
                break;
            case R.id.btn_transition_two:
                switchCamera();
                break;
            case R.id.btn_present_two:
                //送礼物
                showLoadingDialog();
                MainSocialContactModel.getSelectByGsPresentPageList(new ApiModel.CommonCallback<GivePresentBean>() {
                    @Override
                    public void onSuccess(GivePresentBean givePresentBean) {
                        hideLoadingDialog();
                        GiveListBottomSheetDialogFragment giveListBottomSheetDialogFragment = new GiveListBottomSheetDialogFragment(givePresentBean.getData().getList(), userId, videoTvNickName.getText().toString());
                        giveListBottomSheetDialogFragment.setGiveListBottomSheetDialogFragmentInterface(new GiveListBottomSheetDialogFragment.GiveListBottomSheetDialogFragmentInterface() {
                            @Override
                            public void gift(double price) {
                                giftPrice += price;
                            }

                            @Override
                            public void giftShowDialog(boolean show) {
                                if (show) {
                                    showLoadingDialog();
                                } else {
                                    hideLoadingDialog();
                                }
                            }
                        });
                        giveListBottomSheetDialogFragment.show(getSupportFragmentManager(), "giveListBottomSheetDialogFragment");
                    }

                    @Override
                    public void onError(String errMsg) {
                        ToastUtils.showShort(errMsg + "");
                        hideLoadingDialog();
                    }
                });
                break;
//            case R.id.iv_mute:
//                //静音
//                if (isMuteState) {
//                    ImageView muteImage = findViewById(R.id.iv_mute);
//                    muteImage.setImageResource(R.mipmap.em_icon_mute_normal);
//                    try {
//                        EMClient.getInstance().callManager().resumeVoiceTransfer();
//                    } catch (HyphenateException e) {
//                        e.printStackTrace();
//                    }
//                    isMuteState = false;
//                } else {
//                    ImageView muteImage = findViewById(R.id.iv_mute);
//                    muteImage.setImageResource(R.mipmap.em_icon_mute_on);
//                    try {
//                        EMClient.getInstance().callManager().pauseVoiceTransfer();
//                    } catch (HyphenateException e) {
//                        e.printStackTrace();
//                    }
//                    isMuteState = true;
//                }
//                break;
//            case R.id.iv_handsfree:
//                //扬声器
//                if (isHandsfreeState) {
//                    ImageView handsFreeImage = findViewById(R.id.iv_handsfree);
//                    handsFreeImage.setImageResource(R.mipmap.em_icon_speaker_normal);
//                    closeSpeakerOn();
//                    isHandsfreeState = false;
//                } else {
//                    ImageView handsFreeImage = findViewById(R.id.iv_handsfree);
//                    handsFreeImage.setImageResource(R.mipmap.em_icon_speaker_on);
//                    openSpeakerOn();
//                    isHandsfreeState = true;
//                }
//                break;
            default:
        }
    }

    private void addCallStateListener() {
        callStateListener = (callState, callError) -> {
            Log.e("环信", "callState:" + callState.name() + ",callError：" + callError.name());
            switch (callState) {
                case CONNECTING: // 正在连接对方
                    break;
                case CONNECTED: // 双方已经建立连接
                    mHandler.sendEmptyMessage(1);
                    break;
                case ACCEPTED: // 电话接通成功
                    mHandler.sendEmptyMessage(2);
                    break;
                case DISCONNECTED: // 电话断了
                    mHandler.sendEmptyMessage(3);
                    break;
                case NETWORK_UNSTABLE: //网络不稳定
                    if (callError == EMCallStateChangeListener.CallError.ERROR_NO_DATA) {
                        //无通话数据
                    } else {
                    }
                    break;
                case NETWORK_NORMAL: //网络恢复正常
                    break;
                default:
                    break;
            }
            //错误状态
            switch (callError) {
                case REJECTED:
                    mHandler.sendEmptyMessage(4);
                    break;
                case ERROR_BUSY:
                    mHandler.sendEmptyMessage(5);
                    break;
                case ERROR_NORESPONSE:
                    mHandler.sendEmptyMessage(6);
                    break;
                case ERROR_NO_DATA:
                    mHandler.sendEmptyMessage(7);
                    break;
                case ERROR_UNAVAILABLE:
                    mHandler.sendEmptyMessage(8);
                    break;
            }
        };

        EMClient.getInstance().callManager().addCallStateChangeListener(callStateListener);
    }

    /**
     * 结束扣费
     */
    private void finishChat() {
        if (mPresenter != null && liveId != null) {
            showLoadingDialog(false);
            mPresenter.addOrUpdateVideo(userId, 2, liveId);
        } else {
            finish();
        }
    }

    /**
     * 定时器扣费
     */
    private void timerDeduction() {
        if (mPresenter != null && liveId != null) {
            mPresenter.addOrUpdateVideo(userId, liveId);
        }
    }

    @Override
    protected void onDestroy() {
        finishChat();
//        newEndCall();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        super.onDestroy();
    }

    @Override
    public void onLoadLiveSuccess(int status, String result) {
        hideLoadingDialog();
        try {
            if (result != null) {
                LiveResultBean liveResultBean = JSON.parseObject(result, LiveResultBean.class);
                if (liveResultBean != null) {
                    if ("200".equals(liveResultBean.getStatus()) || "202".equals(liveResultBean.getStatus())) {
                        if (status == 1) {
                            liveId = liveResultBean.getLiveId();
                        } else if (status == 2) {
                            //结束
                            TextView tvTime = findViewById(R.id.tv_time);
                            liveEndCallSheetDialogFragment = new LiveEndCallSheetDialogFragment(mMyPersonalBean, liveResultBean, tvTime.getText().toString(), giftPrice);
                            liveEndCallSheetDialogFragment.setLiveEndCallSheetDialogFragmentInterface(new LiveEndCallSheetDialogFragment.LiveEndCallSheetDialogFragmentInterface() {
                                @Override
                                public void checked(HashMap<String, String> data, int score) {
                                    if (data.size() > 0) {
                                        StringBuffer buffer = new StringBuffer();
                                        Collection<String> list = data.values();
                                        int i = 0;
                                        for (String s : list) {
                                            buffer.append(s);
                                            if (i != list.size() - 1) {
                                                buffer.append(",");
                                            }
                                            i++;
                                        }
                                        String label = buffer.toString();
                                        showLoadingDialog();
                                        mPresenter.updateEvaluate(liveId, label, score);
                                    } else {
                                        showLoadingDialog();
                                        mPresenter.updateEvaluate(liveId, null, score);
                                    }
                                }

                                @Override
                                public void dismiss() {
                                    finish();
                                }
                            });
                            liveEndCallSheetDialogFragment.show(getSupportFragmentManager(), "LiveEndCallSheetDialogFragment");
                        } else if (status == 3) {

                        }
                    } else {
                        ToastUtils.showShort(liveResultBean.getMsg() + "");
                        if (status == 1) {
                            //开通密聊失败 直接退出
                            newEndCallFinish();
                        } else {
                            finishChat();
                        }
                    }
                }
            }
//            if (isEndCall) {
//                finish();
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onLoadLiveFailed(String err) {
        hideLoadingDialog();
        try {
            if (liveEndCallSheetDialogFragment != null) {
                liveEndCallSheetDialogFragment.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        if (isEndCall) {
//            finish();
//        }
    }

    @Override
    public void onCommentSuccess(WithDrawResultBean result) {
        hideLoadingDialog();
        try {
            if (liveEndCallSheetDialogFragment != null) {
                liveEndCallSheetDialogFragment.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ToastUtils.showShort("评价成功");
        finish();

    }

    @Override
    public void onCommentFailed(String err) {
        hideLoadingDialog();
        try {
            if (liveEndCallSheetDialogFragment != null) {
                liveEndCallSheetDialogFragment.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finish();
    }

}
